import { getRouters } from "../../api/menu";
import { SET_ROUTES, SET_SIDEBAR_ROUTERS, GENERATE_ROUTES } from "../constant";

// 导出一个名为generateRoutes的函数
// 导出一个名为generateRoutes的函数
export const generateRoutes = () => {
  // 返回一个异步函数
  return (dispatch) => {
    //return new Promise((resolve, reject) => {
        // 调用getRouters函数获取路由数据
      // 将路由数据深拷贝一份
     return getRouters().then((response) => {
        const sdata = JSON.parse(JSON.stringify(response.data));
        // 调用filterAsyncRouter函数过滤异步路由
        const rdata = JSON.parse(JSON.stringify(response.data));
        const sidebarRoutes = filterAsyncRouter(sdata);
        // 调用getLeafNodes函数获取叶子节点
        const rewriteRoutes = filterAsyncRouter(rdata, false, true);
        // 调用dispatch函数分发action
        const leafRouters = getLeafNodes(rewriteRoutes);
        dispatch({
          type: GENERATE_ROUTES,
          data: { routes: rewriteRoutes, sidebarRouters: sidebarRoutes, leafRouters: leafRouters },
        });
        //console.log('=======getRouters==leafRouters')
        //resolve(leafRouters);
        return leafRouters;
        }).catch((err) => {
          //console.log('=========eer',err);
          //reject(err)
          throw err;
        })
        // 捕获错误并打印
   // })
      
  };
};

function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
    return asyncRouterMap.filter(route => {
        if (type && route.children) {
            route.children = filterChildren(route.children)
          }
        // if(route.component === 'Layout') {
        //     route.component = Layout
        // } else {
        //     route.component = loadView(route.component)
        //   }
        if (route.children != null && route.children && route.children.length) {
            route.children = filterAsyncRouter(route.children, route, type)
        } else {
            delete route['children']
            delete route['redirect']
        }
        return true
    })
}

function filterChildren(childrenMap, lastRouter = false) {
    var children = []
    childrenMap.forEach((el, index) => {
        if (el.children && el.children.length) {
            if (el.component == 'ParentView' && !lastRouter) {
                el.children.forEach(child => {
                    child.path = el.path + '/' + child.path
                    if(child.children && child.children.length) {
                        children = children.concat(filterChildren(child.children, child))
                        return
                    }
                    children.push(child)
                    
                })
                return
            }
        }
        if (lastRouter) {
            el.path = lastRouter.path + '/' + el.path
            if (el.children && el.children.length) {
                children = children.concat(filterChildren(el.children, el))
                return
            }
        }
        children = children.concat(el)
    });
    return children
}


function getLeafNodes(routes) {
    let leafNodes = [];

    function recurse(nodes) {
        nodes.forEach(node => {
            //检查是否有子节点
            if (node.children && node.children.length > 0) {
                //如果有子节点，则递归调用recurse函数
                recurse(node.children);
            } else {
                //如果没有子节点，则将节点添加到leafNodes数组中
                leafNodes.push(node);
            }
        });
    }

    recurse(routes);

    return leafNodes;
}